package lock;

import java.util.concurrent.Semaphore;

/**
 * 案例：基于信号量Semaphore实现主线程阻塞等待所有子线程特定任务执行完毕
 */
public class SemaphoreTest {

    public static void main(String[] args) throws InterruptedException {
        //内部sync同步器的state值设为0
        Semaphore semaphore = new Semaphore(0);

        for (int i = 1;i <= 5;i++) {
            new Thread(() -> {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    System.out.println("目标代码块运行完毕");
                    //每调用一次release()内部调用releaseShared(1)都会使state值增一
                    semaphore.release();
                }
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("线程结束");
            }).start();
        }
        System.out.println("所有线程已启动");
        //主线程调用acquire(int permits)方法后若无法获取到足够的资源就会进入阻塞，
        // 直到所有线程调用了semaphore.release()使state值增为所需值，或者主线程被中断，才会从阻塞返回
        semaphore.acquire(3);
        System.out.println("所有线程目标代码块已运行完毕");
    }
}
